﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Data;
using System.Web.UI.WebControls;
using Utility.Helper;

namespace Thksoft.Modal
{
    public partial class BankBillsLedgerEdit : BasePage
    {
        private BankBillsLedgerBLL bll = new BankBillsLedgerBLL();
        private YX_TradeBillBLL tb = new YX_TradeBillBLL();
        private YX_BankCheckBLL bc = new YX_BankCheckBLL();
        private YX_TransferChequeBLL tc = new YX_TransferChequeBLL();
        private YX_CashChequeBLL cc = new YX_CashChequeBLL();
        private Sys_UserBLL user = new Sys_UserBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["Select"] == "true")
                {
                    btnSave.Visible = false;
                }
                else
                {
                    btnSave.Visible = true;
                }
                txtDateStart.Value = DateTime.Now.ToString("yyyy-MM-dd");

                BindBank();
                BindCompany();

                if (!string.IsNullOrEmpty(Request.QueryString["ID"]) && !string.IsNullOrEmpty(Request.QueryString["Type"]))
                {
                    BindData();
                }
            }
        }

        /// <summary>
        /// 修改绑定数据
        /// </summary>
        public void BindData()
        {
            var id = Convert.ToInt32(Request.QueryString["ID"].ToString());
            var type1 = Convert.ToInt32(Request.QueryString["Type"].ToString());
            IYX_Bill_Base bill_Base;
            var model = bll.SelectById(id, type1, out bill_Base);
            FORM_BANK_ID.SelectedValue = bill_Base.DE_BANK_ID.ToString() == null ? "1" : bill_Base.DE_BANK_ID.ToString();
            FORM_COMPANY_ID.SelectedValue = bill_Base.DE_COMPANY_ID.ToString();
            //出票人
            BindUser(FORM_COMPANY_ID.SelectedValue);

            txtZnum.Value = bill_Base.ACCOUNT.ToString();
            txtRemark.Text = bill_Base.REMARK;
            txtPayee.Value = bill_Base.PAYEENAME.ToString();
            txtBillnum.Text = bill_Base.DE_CODE.ToString();
            txtamont1.Value = bill_Base.PAY_AMOUNT.ToString();
            txtDateStart.Value = bill_Base.START_DATE == null ? "" : bill_Base.START_DATE.Value.ToString("yyyy-MM-dd");

            #region 票据判断

            string type = type1.ToString();
            switch (type)
            {
                case "1":
                    lblTYPE.Text = "商业汇票";
                    {
                        YX_TradeBill ss = bill_Base as YX_TradeBill;
                        txtPayeeBank.Value = ss.C_TRADEBILL_PAYEEBANKNAME.ToString();
                        txtPayeeCompany.Value = ss.C_TRADEBILL_PAYEECMYNAME.ToString();
                        txtDfzh.Value = ss.C_TRADEBILL_PAYEEACCOUNT.ToString();
                        FORM_Drawer.Text = ss.N_TRADEBILL_DRAWERID.ToString();
                        //var users=user.Find(ss.N_TRADEBILL_DRAWERID);
                        //if (users!=null)
                        //{
                        //    txtDrawer.Value = users.USER_NAME.ToString();
                        //}
                        //else
                        //{
                        //    MessageBox.Show(Page, "没有此出票人！");
                        //}
                        txtDateEnd.Value = ss.D_TRADEBILL_ENDDATE == null ? "" : ss.D_TRADEBILL_ENDDATE.ToString("yyyy-MM-dd");
                        txtPayerName.Value = ss.C_TRADEBILL_PAYERNAME.ToString();
                    }
                    break;

                case "2":
                    lblTYPE.Text = "银行本票";
                    {
                        YX_BankCheck ss = bill_Base as YX_BankCheck;
                        ddlCheckType.SelectedValue = ss.N_BANKCHECK_TYPE.ToString();
                        FORM_Drawer.Text = ss.N_BANKCHECK_USERID.ToString();
                    }
                    break;

                case "3":
                    lblTYPE.Text = "转账支票";
                    {
                        YX_TransferCheque ss = bill_Base as YX_TransferCheque;
                        txtPayeeBank.Value = ss.C_TFCHEQUE_PAYEEBANK.ToString();
                        txtPayeeCompany.Value = ss.C_TFCHEQUE_PAYEECMP.ToString();
                        txtDfzh.Value = ss.C_TFCHEQUE_PAYEEACCOUNT.ToString();
                    }
                    break;

                case "4":
                    lblTYPE.Text = "现金支票";
                    {
                        YX_CashCheque ss = bill_Base as YX_CashCheque;
                        txtPROJECTNAME.Text = ss.C_CASHCHEQUE_USE.ToString();
                    }
                    break;

                default:
                    lblTYPE.Text = "银行票据台账";
                    break;
            }

            #endregion 票据判断

            if (model != null)
            {
                txtPayeeNumber.Value = model.C_PAYEENUMBER.ToString() == null ? "" : model.C_PAYEENUMBER.ToString();
                txtPROJECTCODE.Text = model.N_TERMOFBILL.ToString();
                txtPROJECTCODE.Text = model.C_PROJECTCODE.ToString();
                txtPROJECTNAME.Text = model.C_PROJECTNAME.ToString();
                txtPayeeBank.Value = model.C_PAYEEBANKNAME.ToString();
                txtPayeeCompany.Value = model.C_PAYEECMYNAME.ToString();
                txtDfzh.Value = model.C_PAYEEACCOUNT.ToString();
                FORM_Drawer.Text = model.N_DRAWERUSERID.ToString();
                //var users = user.Find(model.N_DRAWERUSERID);
                //if (users != null)
                //{
                //    txtDrawer.Value = users.USER_NAME.ToString();
                //}
                //else
                //{
                //    MessageBox.Show(Page, "没有此出票人！");
                //}
                txtPayerName.Value = model.C_DRAWEENAME.ToString();
                ddlCheckType.SelectedValue = model.N_IFOFFER.ToString();
                txtDateEnd.Value = model.D_ENDDATE == null ? "" : model.D_ENDDATE.ToString("yyyy-MM-dd");
                txtTERMOFBILL.Value = model.N_TERMOFBILL.ToString();
                txtACCEPTANCETIME.Value = model.D_ACCEPTANCETIME == null ? "" : model.D_ACCEPTANCETIME.ToString("yyyy-MM-dd");
                txtCOLLECTTICKETSTIME.Value = model.D_COLLECTTICKETSTIME == null ? "" : model.D_COLLECTTICKETSTIME.ToString("yyyy-MM-dd");
                PurchaseDate.Value = model.D_PURCHASEDATE == null ? "" : model.D_PURCHASEDATE.DateFormat("yyyy-MM-dd");
                ddlPayType.SelectedValue = model.N_PAYTYPE.ToString();
            }
        }

        #region 初次加载公司和银行与用户

        /// <summary>
        /// 得到汇票银行
        /// </summary>
        public void BindBank()
        {
            int count;

            var dt = new Sys_BankBLL().GetEntitys(null, null, 0, 1000, out count);

            FORM_BANK_ID.DataSource = dt;
            FORM_BANK_ID.DataTextField = "C_NAME";
            FORM_BANK_ID.DataValueField = "N_ID";
            FORM_BANK_ID.DataBind();
            FORM_BANK_ID.Items.Insert(0, new ListItem("---请选择---", "-1"));

            FORM_BANK_ID.SelectedValue = "-1";
        }

        /// <summary>
        /// 得到汇票公司
        /// </summary>
        public void BindCompany()
        {
            int count;

            string whereStr = @" CMY_ID in (select cp.cmy_id
  from sys_company cp
 start with cp.cmy_id = " + lognUser.USER_COMPANY + @"
connect by prior cp.cmy_id = cp.cmy_parentid) ";

            var dt = new Sys_CompanyBLL().GetEntitys(whereStr, null, 0, 1000, out count);

            FORM_COMPANY_ID.DataSource = dt;
            FORM_COMPANY_ID.DataTextField = "CMY_NAME";
            FORM_COMPANY_ID.DataValueField = "CMY_ID";
            FORM_COMPANY_ID.DataBind();
            FORM_COMPANY_ID.Items.Insert(0, new ListItem("---请选择---", "-1"));

            FORM_COMPANY_ID.SelectedValue = "-1";
        }

        /// <summary>
        /// 根据公司ID得到用户
        /// </summary>
        /// <param name="cmyId"></param>
        public void BindUser(string cmyId)
        {
            var dt = user.GetNameByCmyId(cmyId);
            this.FORM_Drawer.DataSource = dt;
            this.FORM_Drawer.DataTextField = "user_name";
            this.FORM_Drawer.DataValueField = "user_id";
            this.FORM_Drawer.DataBind();
            this.FORM_Drawer.Items.Insert(0, new ListItem("---请选择---", "-1"));
            //foreach (var item in dt.AsEnumerable())
            //{
            //    this.FORM_Drawer.Items.Add(new ListItem(item["user_name"].ToString(), item["user_id"].ToString()));
            //}
        }

        #endregion 初次加载公司和银行与用户

        protected void btnSave_Click(object sender, EventArgs e)
        {
            #region 编辑条件

            if (FORM_COMPANY_ID.SelectedValue.ToString() == "-1")
            {
                MessageBox.Show(Page, "请选择出票人公司名称");
                return;
            }
            if (FORM_BANK_ID.SelectedValue.ToString() == "-1")
            {
                MessageBox.Show(Page, "请选择出票人银行名称");
                return;
            }
            if (txtZnum.Value.Trim() == "")
            {
                MessageBox.Show(Page, "出票人账号不能为空");
                return;
            }

            if (txtPayee.Value.Trim() == "")
            {
                MessageBox.Show(Page, "收款人不能为空");
                return;
            }

            if (txtamont1.Value.Trim() == "")
            {
                MessageBox.Show(Page, "出票金额不能为空");
                return;
            }
            else
            {
                decimal je = 0;
                if (!decimal.TryParse(txtamont1.Value.Trim(), out je))
                {
                    MessageBox.Show(Page, "出票金额必须是数字");
                    return;
                }
                else
                {
                    if (Convert.ToDecimal(txtamont1.Value.Trim()) > 10000000)
                    {
                        MessageBox.Show(Page, "票面金额最高为1000万元");
                        return;
                    }
                }
            }

            if (txtDateStart.Value.Trim() == "")
            {
                MessageBox.Show(Page, "出票日期不能为空");
                return;
            }

            if (txtBillnum.Text.Trim() == "")
            {
                MessageBox.Show(Page, "票据编号不能为空");
                return;
            }

            bool mainName = SelectMethod();
            if (mainName == false)
            {
                MessageBox.Show(Page, "主账户要与银行账户设置相匹配,且必须为支出户!");
                return;
            }

            #endregion 编辑条件

            var id = Convert.ToInt32(Request.QueryString["ID"].ToString());
            var type1 = Convert.ToInt32(Request.QueryString["Type"].ToString());

            //decimal userID;
            //if (!string.IsNullOrEmpty(txtDrawer.Value.Trim().ToString()))
            //{
            //    string sql = string.Format(@"select * from sys_user where user_name = '{0}' and user_company={1}", txtDrawer.Value.Trim(), decimal.Parse(FORM_COMPANY_ID.SelectedValue));
            //    var username = user.FirstOrDefaultQuery(sql);
            //    if (username == null)
            //    {
            //        MessageBox.Show(Page, "出票公司没有此出票人！");
            //        return;
            //    }
            //    else
            //    {
            //        userID = decimal.Parse(username["USER_ID"].ToString());
            //    }
            //}
            //else
            //{
            //    MessageBox.Show(Page, "出票人不能为空！");
            //    return;
            //}

            #region 各票据数据修改

            var count = 0;
            string type = type1.ToString();
            switch (type)
            {
                case "1":
                    lblTYPE.Text = "商业汇票";
                    {
                        var ss = new YX_TradeBill();
                        ss.N_TRADEBILL_ID = id;
                        ss.D_TRADEBILL_STARTDATE = DateTime.Parse(txtDateStart.Value);
                        ss.N_TRADEBILL_DRAWERBANKID = decimal.Parse(FORM_BANK_ID.SelectedValue);
                        ss.N_TRADEBILL_DRAWERCMYID = decimal.Parse(FORM_COMPANY_ID.SelectedValue);
                        ss.C_TRADEBILL_DRAWERACCOUNT = txtZnum.Value.Trim();
                        ss.N_TRADEBILL_INVOICEVALUE = decimal.Parse(txtamont1.Value);
                        ss.C_TRADEBILL_CODE = txtBillnum.Text.Trim();
                        ss.C_TRADEBILL_REMARK = txtRemark.Text.Trim();
                        ss.C_TRADEBILL_PAYEENAME = txtPayee.Value.Trim();

                        ss.C_TRADEBILL_PAYEEBANKNAME = txtPayeeBank.Value.Trim();
                        ss.C_TRADEBILL_PAYEECMYNAME = txtPayeeCompany.Value.Trim();
                        ss.C_TRADEBILL_PAYEEACCOUNT = txtDfzh.Value.Trim();
                        ss.N_TRADEBILL_DRAWERID = Convert.ToDecimal(FORM_Drawer.Text);//userID;
                        ss.D_TRADEBILL_ENDDATE = DateTime.Parse(txtDateEnd.Value);
                        ss.C_TRADEBILL_PAYERNAME = txtPayerName.Value.Trim();

                        count = tb.UPDATE(ss, CurrentUserName);
                        if (count == 0)
                        {
                            MessageBox.Show(Page, "编辑失败");
                            return;
                        }
                    }
                    break;

                case "2":
                    lblTYPE.Text = "银行本票";
                    {
                        var ss = new YX_BankCheck();
                        ss.N_BANKCHECK_ID = id;
                        ss.D_BANKCHECK_DATE = DateTime.Parse(txtDateStart.Value);
                        ss.N_BANKCHECK_BANKID = decimal.Parse(FORM_BANK_ID.SelectedValue);
                        ss.N_BANKCHECK_CMYID = decimal.Parse(FORM_COMPANY_ID.SelectedValue);
                        ss.C_BANKCHECK_ACCOUNTNUMBER = txtZnum.Value.Trim();
                        ss.N_BANKCHECK_MONEY = decimal.Parse(txtamont1.Value);
                        ss.C_BANKCHECK_CODE = txtBillnum.Text.Trim();
                        ss.C_BANKCHECK_REMARK = txtRemark.Text.Trim();
                        ss.C_BANKCHECK_NAMEPAYEE = txtPayee.Value.Trim();
                        ss.N_BANKCHECK_USERID = Convert.ToDecimal(FORM_Drawer.Text);//userID;
                        ss.N_BANKCHECK_TYPE = decimal.Parse(ddlPayType.SelectedValue);
                        count = bc.UPDATE(ss, CurrentUserName);
                        if (count == 0)
                        {
                            MessageBox.Show(Page, "编辑失败");
                            return;
                        }
                    }
                    break;

                case "3":
                    lblTYPE.Text = "转账支票";
                    {
                        var ss = new YX_TransferCheque();
                        ss.N_TFCHEQUE_ID = id;
                        ss.D_TFCHEQUE_STARTDATE = DateTime.Parse(txtDateStart.Value);
                        ss.N_TFCHEQUE_DRAWERBANKID = decimal.Parse(FORM_BANK_ID.SelectedValue);
                        ss.N_TFCHEQUE_DRAWERCMPID = decimal.Parse(FORM_COMPANY_ID.SelectedValue);
                        ss.C_TFCHEQUE_DRAWERACCOUNT = txtZnum.Value.Trim();
                        ss.N_TFCHEQUE_INVOICEVALUE = decimal.Parse(txtamont1.Value);
                        ss.C_TFCHEQUE_CODE = txtBillnum.Text.Trim();
                        ss.C_TFCHEQUE_REMARK = txtRemark.Text.Trim();
                        ss.C_TFCHEQUE_PAYEENAME = txtPayee.Value.Trim();

                        ss.C_TFCHEQUE_PAYEEBANK = txtPayeeBank.Value.Trim();
                        ss.C_TFCHEQUE_PAYEECMP = txtPayeeCompany.Value.Trim();
                        ss.C_TFCHEQUE_PAYEEACCOUNT = txtDfzh.Value.Trim();
                        count = tc.UPDATE(ss, CurrentUserName);
                        if (count == 0)
                        {
                            MessageBox.Show(Page, "编辑失败");
                            return;
                        }
                    }
                    break;

                case "4":
                    lblTYPE.Text = "现金支票";
                    {
                        var ss = new YX_CashCheque();
                        ss.N_CASHCHEQUE_ID = id;
                        ss.D_CASHCHEQUE_STARTDATE = DateTime.Parse(txtDateStart.Value);
                        ss.N_CASHCHEQUE_DRAWERBANKID = decimal.Parse(FORM_BANK_ID.SelectedValue);
                        ss.N_CASHCHEQUE_DRAWERCMPID = decimal.Parse(FORM_COMPANY_ID.SelectedValue);
                        ss.C_CASHCHEQUE_DRAWERACCOUNT = txtZnum.Value.Trim();
                        ss.N_CASHCHEQUE_INVOICEVALUE = decimal.Parse(txtamont1.Value);
                        ss.C_CASHCHEQUE_CODE = txtBillnum.Text.Trim();
                        ss.C_CASHCHEQUE_REMARK = txtRemark.Text.Trim();
                        ss.C_CASHCHEQUE_PAYEENAME = txtPayee.Value.Trim();

                        ss.C_CASHCHEQUE_USE = txtPROJECTNAME.Text.Trim();
                        count = cc.UPDATE(ss, CurrentUserName);
                        if (count == 0)
                        {
                            MessageBox.Show(Page, "编辑失败");
                            return;
                        }
                    }
                    break;

                default:
                    lblTYPE.Text = "银行票据台账";
                    break;
            }

            #endregion 各票据数据修改

            var bill = bll.SelectById(id, type1);

            var model = new YX_BillsLedger();
            var status = false;
            if (bill != null)
            {
                status = true;
                model.N_ID = bill.N_ID;
            }
            else
            {
                model.N_ID = 1;
            }

            model.D_ENDDATE = Convert.ToDateTime(txtDateEnd.Value == "" ? null : txtDateEnd.Value);//DateTime.Parse(txtDateEnd.Value);"yyyy-mm-dd hh24:MI:ss"
            model.C_PAYEEBANKNAME = txtPayeeBank.Value.Trim();
            model.C_PAYEECMYNAME = txtPayeeCompany.Value.Trim();
            model.C_PAYEEACCOUNT = txtDfzh.Value.Trim();
            model.N_IFOFFER = decimal.Parse(ddlCheckType.SelectedValue);
            model.C_DRAWEENAME = txtPayerName.Value.Trim();
            model.C_PAYEENUMBER = txtPayeeNumber.Value.Trim();
            model.C_PROJECTCODE = txtPROJECTCODE.Text;
            model.C_PROJECTNAME = txtPROJECTNAME.Text.Trim();
            model.D_ACCEPTANCETIME = Convert.ToDateTime(txtACCEPTANCETIME.Value == "" ? null : txtACCEPTANCETIME.Value);
            model.D_COLLECTTICKETSTIME = Convert.ToDateTime(txtCOLLECTTICKETSTIME.Value == "" ? null : txtCOLLECTTICKETSTIME.Value);
            model.N_TERMOFBILL = Convert.ToDecimal(txtTERMOFBILL.Value.Trim() == "" ? null : txtTERMOFBILL.Value.Trim());
            model.D_PURCHASEDATE = Convert.ToDateTime(PurchaseDate.Value == "" ? null : PurchaseDate.Value);
            model.N_PAYTYPE = decimal.Parse(ddlPayType.SelectedValue);
            model.N_TYPE = type1;
            model.N_BILL_ID = id;
            model.N_DRAWERUSERID = Convert.ToDecimal(FORM_Drawer.Text);//userID;

            if (status)
            {
                try
                {
                    if (bll.UPDATE(model, CurrentUserName) && count > 0)
                    {
                        MessageBox.Show(Page, "编辑成功！");
                    }
                    else
                    {
                        MessageBox.Show(Page, "编辑失败！");
                        return;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(Page, "编辑失败！");
                }
            }
            else
            {
                if (bll.Insert(model, CurrentUserName) && count > 0)
                {
                    MessageBox.Show(Page, "编辑成功！");
                }
                else
                {
                    MessageBox.Show(Page, "编辑失败！");
                    return;
                }
            }
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            MessageBox.ResponseScript(this, "FORM_CLOSE();");
        }

        /// <summary>
        /// 根据输入的主账号查询银行账户设置的主账号
        /// </summary>
        private bool SelectMethod()
        {
            BaseBLL bsBLL = new BaseBLL();
            DataTable dt = null;
            string mainName = this.txtZnum.Value.Trim().ToString();

            string sql = " and a.accountno = '" + mainName + "'";

            {
                string _sql = @"select a.accounti_id accountId,
       c.cmy_name companyName,
       d.deptname depName,
       decode(a.accounttype, 1, '支出户', 2, '收入户') accType,
       a.accountno accountNo,
       b.c_name openBank
  from sys_company c, sys_department d, yx_account a,sys_bank b
 where c.cmy_id = d.cmy_id
   and c.cmy_id = a.company_id
   and d.deptid = a.department_id
   and a.n_bank_id=b.n_id
   and a.accounttype=1";
                if (_sql != "")
                {
                    _sql += sql;
                }
                dt = bsBLL.Query(_sql);
            }

            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected void FORM_COMPANY_ID_SelectedIndexChanged(object sender, EventArgs e)
        {
            string cmyId = FORM_COMPANY_ID.SelectedValue.ToString();
            BindUser(cmyId);
        }
    }
}